import React, { useState, useMemo, useCallback } from "react";

const Child = React.memo(function (props) {
    console.log("子组件渲染了 render ");
    return (
        <div>
            Child
            <button onClick={props.onClick}>点击子组件</button>
        </div>
    );
});

function App() {
    const [count, setCount] = useState(0);
    const [random, setRandom] = useState(0);

    // useMemo 缓存的不是函数而是函数的返回值
    // useCallback 缓存的是函数体
    // 依赖值用useMemo，依赖函数用useCallback
    // useMemo返回一个函数就相当于useCallback useCallback => useMemo(() => fn)
    //  useMemo 可以缓存值同样的也可以缓存一个函数
    const fn = useMemo(
        () => () => {
            console.log("点击了子组件");
        },
        []
    );
    // console.log(fn);

    return (
        <div>
            <p>随机数: {random}</p>
            <p>count: {count}</p>

            <button
                onClick={() => {
                    setCount(count + 1);
                }}>
                count + 1
            </button>
            <button
                onClick={() => {
                    setRandom(Math.random());
                }}>
                生成随机数
            </button>
            <Child onClick={fn}></Child>
        </div>
    );
}

export default App;
